#!/usr/bin/python
# -*- coding: UTF-8 -*-

#批量转换doc文件为docx文件或pdf文件
from win32com import client
import os
import re
import xlrd
import xlwt

#批量转换主程序，填写文件夹位置，填写转换格式目录生，会在文件夹同级生成convert文件夹，存放转换后文件
#path填写文件夹路径，format填写所需转换格式
#下面党的pathconfig、doc2docx、doc2pdf、doc2html都是批量转换相关程序
def batchconvert(path,format):
    """
    wdFormatDocument = 0
    wdFormatDocument97 = 0
    wdFormatDocumentDefault = 16
    wdFormatDOSText = 4
    wdFormatDOSTextLineBreaks = 5
    wdFormatEncodedText = 7
    wdFormatFilteredHTML = 10
    wdFormatFlatXML = 19
    wdFormatFlatXMLMacroEnabled = 20
    wdFormatFlatXMLTemplate = 21
    wdFormatFlatXMLTemplateMacroEnabled = 22
    wdFormatHTML = 8
    wdFormatPDF = 17
    wdFormatRTF = 6
    wdFormatTemplate = 1
    wdFormatTemplate97 = 1
    wdFormatText = 2
    wdFormatTextLineBreaks = 3
    wdFormatUnicodeText = 7
    wdFormatWebArchive = 9
    wdFormatXML = 11
    wdFormatXMLDocument = 12
    wdFormatXMLDocumentMacroEnabled = 13
    wdFormatXMLTemplate = 14
    wdFormatXMLTemplateMacroEnabled = 15
    wdFormatXPS = 18
    """
    if not os.path.exists(path):
        return 'path is not exist'
    convert_path = pathconfig(path) + "convert"
    if not os.path.exists(convert_path):
        os.makedirs(convert_path)
    print(convert_path)
    if format == 'docx':
        files = os.listdir(path)
        for file in files:
            filename = path + '\\' + file
            if file[-4:] == '.doc':
                convertfilename = file[:-4] + '.docx'
            else:
                return 'file is not doc'
            convertname = convert_path + '\\' + convertfilename
            print('filename is ' + filename)
            print('convert filename is ' + convertname)
            print(doc2docx(filename, convertname))
    elif format == 'pdf':
        files = os.listdir(path)
        for file in files:
            filename = path + '\\' + file
            if file[-4:] == '.doc':
                convertfilename = file[:-4] + '.pdf'
            else:
                return 'file is not doc'
            convertname = convert_path + '\\' + convertfilename
            print('filename is ' + filename)
            print('convert filename is ' + convertname)
            print(doc2pdf(filename, convertname))
    else :
        return 'format is not suport'

#返回输入路径的上级目录
def pathconfig(path):
    print(path)
    end = '\\'
    if path.find(end) >= 0:
        endnum = path.rfind(end)
    else:
        return "first path has no '\\'"
    path_before = path[:endnum +1]
    """
    if path1.find(end) >= 0:
        endnum = path1.rfind(end)
    else:
        return "second path has no '\\'"
    path2 = path1[:endnum+1]
    """
    return(path_before)

#doc转docx
def doc2docx(doc_name,docx_name = None):

    print('doc2docx ' + 'gets docname is ' + doc_name)
    try:
        #print('原始文件名：' + doc_name)
        word = client.Dispatch("Word.Application")
        if docx_name == None:
            docx_name = doc_name[:-4] + '.docx'
            print('docxname is ' + docx_name)
        if os.path.exists(docx_name):
            os.remove(docx_name)
        doc = word.Documents.Open(doc_name, ReadOnly = 1)
        doc.SaveAs(docx_name,16)
        doc.Close()
        word.Quit()
    except:
        pass
    return '原始文件：' + doc_name + '\r\n' + '转换后文件：' + docx_name + '\r\n' + 'success'

#doc转pdf
def doc2pdf(doc_name,pdf_name = None):
    print('doc2pdf ' + 'gets docname is ' + doc_name)
    try:
        word = client.Dispatch("Word.Application")
        if pdf_name == None:
            pdf_name = doc_name[:-4] + '.pdf'
            print('pdfname is ' + pdf_name)
        if os.path.exists(pdf_name):
            os.remove(pdf_name)
        doc = word.Documents.Open(doc_name,ReadOnly = 1)
        doc.SaveAs(pdf_name,17)
        doc.Close()
        word.Quit()
    except:
        pass
    return '原始文件：' + doc_name + '\r\n' + '转换后文件：' + pdf_name + '\r\n' + 'success'

#doc转html
def doc2html(doc_name,html_name = None):

    try:
        word = client.Dispatch("Word.Application")
        if os.path.exists(html_name):
            os.remove(html_name)
        doc = word.Documents.Open(doc_name,ReadOnly = 1)
        doc.SaveAs(html_name,8)
        doc.Close()
        word.Quit()
    except:
        pass

#标准化文件名，把不标准括号修正，把多余空格去掉
#oath填写文件夹目录,仍有问题，会重复修改，随后再更新
def iteration(path):
    if os.path.isdir(path):
        print('path 是路径:' + path)
        old_files = os.listdir(path)
        for old_file in old_files:
            print(path + "路径下文件或路径：" + old_file)
            old_path = path + "\\" + old_file
            new_file = old_file
            if os.path.isfile(old_path):
                print("确认"+ old_path + "是文件")
                #会把不是年份的相关括号给换掉，后期需修正
                if new_file.find(' ') >= 0 :
                    new_file = new_file.replace(' ', '')
                if re.findall(r'\（20\d{2}\）\d+号', new_file):
                    new_file = new_file.replace('（','〔')
                    new_file = new_file.replace('）', '〕')
                if re.findall(r'\(20\d{2}\)\d+号',new_file):
                    new_file = new_file.replace('(', '〔')
                    new_file = new_file.replace(')', '〕')
                if re.findall(r'\[20\d{2}\]\d+号',new_file):
                    new_file = new_file.replace('[', '〔')
                    new_file = new_file.replace(']', '〕')
                if re.findall(r'[(](.*?)[)]',new_file):
                    new_file = new_file.replace('[', '〔')
                    new_file = new_file.replace(']', '〕')



                if old_file.find(' ') >= 0 \
                        or old_file.find('(') >= 0 or old_file.find(')') >= 0 \
                        or old_file.find('[') >= 0 or old_file.find(']') >= 0 \
                        or re.findall(r'（20\d{2}）', old_file) or re.findall(r'(20\d{2})', old_file) \
                        or re.findall(r'[20\d{2}]', old_file) or re.findall(r'【20\d{2}】', old_file):
                    print("文件名：" + old_file + "中有‘(’‘)’‘[’‘]’‘ ’等不标准符号或不标准年号")
                    new_file = old_file.replace(' ', '')
                    new_file = new_file.replace('(', '（')
                    new_file = new_file.replace(')', '）')
                    new_file = new_file.replace('[', '〔')
                    new_file = new_file.replace(']', '〕')
                    new_file = new_file.replace('（', '〔')
                    new_file = new_file.replace('）', '〕')
                    new_file = new_file.replace('(', '〔')
                    new_file = new_file.replace(')', '〕')
                    try:
                        os.rename(path + '\\' + old_file,path + '\\' + new_file)
                    except:
                        print(old_file + " or " + new_file + ' error!')
                    print("修正完毕后文件名为：" + new_file)
            else:
                iteration(path + "\\" + old_file)

#在excel中查找串包含特殊字符的条数及相应信息
def findmess(list,path,colno = 1):

    relist = []
    row = 0
    dict = {}

    if os.path.isdir(path):
        files = os.listdir(path)
        for file in files:
            index = 0
            print(file)
            filename = path + '\\' + file
            workbook = xlrd.open_workbook(filename)
            sheet = workbook.sheet_by_name("Sheet1")
            rows = sheet.nrows
            row = row + rows
            # print(rows)
            for i in range(rows):
                for code in list:
                    # 因excel中格式固定，用的都是固定列的数据，所以在此固定了列号为1，第二列
                    if code in sheet.cell_value(i, colno) and sheet.cell_value(i, colno) != sheet.cell_value(i - 1,colno) and sheet.cell_value(i, colno) not in relist:
                        # print(sheet.cell_value(i,1))
                        relist.append(sheet.cell_value(i, colno))
                        index = index + 1
            print('条数：' + str(index))
            dict[file] = index
            print('当前共计条数：' + str(row))

    elif os.path.isfile(path):
        index = 0
        print(path)
        workbook = xlrd.open_workbook(path)
        sheet = workbook.sheet_by_name("Sheet1")
        rows = sheet.nrows
        row = row + rows
        # print(rows)
        for i in range(rows):
            for code in list:
                # 因excel中格式固定，用的都是固定列的数据，所以在此固定了列号为1，第二列
                if code in sheet.cell_value(i, colno) and sheet.cell_value(i, colno) != sheet.cell_value(i - 1,
                                                                                                         colno) and sheet.cell_value(
                        i, colno) not in relist:
                    # print(sheet.cell_value(i,1))
                    relist.append(sheet.cell_value(i, colno))
                    index = index + 1
        print('条数：' + str(index))
        print('当前共计条数：' + str(row))

    print(relist)
    print(len(relist))
    print(dict)
    print('全部共计条数：' + str(row))

#将list输出至xls,这里list中需要包含多个list，一个list一列
def mess2xls(lists,path):
    if os.path.exists(path):
        os.remove(path)
    wb = xlwt.Workbook()
    ws = wb.add_sheet('Sheet1')
    for i in range(len(lists)):
        list = lists[i]
        for j in range(len(list)):
            ws.write(j,i,list[j])
    wb.save(path)

